package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.HashMap;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.GooglePlaces;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.Place;
import luanvan.app.foodnote.library.PlacesList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class GooglePlacesActivity extends SherlockActivity {
	
	 AlertDialogManager alert = new AlertDialogManager();
	 private ProgressDialog pDialog;
	 // Google Places
     GooglePlaces googlePlaces;
	 
     // Places List
     PlacesList nearPlaces;
     
	 JSONParser jsonParser = new JSONParser();
	 
	 //private static final String url_food_detials = "http://10.0.2.2/foodnote/get_food_details.php";
	 
	 //private static final String url_food_detials = "http://192.168.0.104/foodnote/get_food_details.php";
	 
	 private double latExtra, lngExtra;
	 // Places Listview
	 ListView lv;
	 
	 private static final String TAG_LATITUDE = "LATITUDE";
     private static final String TAG_LONGITUDE = "LONGITUDE";
     
     // ListItems data
     ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
     // KEY Strings
     public static String KEY_REFERENCE = "reference"; // id of the place
     public static String KEY_NAME = "name"; // name of the place
     public static String KEY_VICINITY = "vicinity"; // Place area name

	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 	requestWindowFeature(Window.FEATURE_LEFT_ICON);
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.googleplaces);
	        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.food_around);
	        
	        lv = (ListView) findViewById(R.id.list);
	        lv.setCacheColorHint(Color.TRANSPARENT);
	        
	        Intent i = getIntent();
	        latExtra = i.getExtras().getDouble(TAG_LATITUDE);
	        lngExtra = i.getExtras().getDouble(TAG_LONGITUDE);
	        
	        if(latExtra != 0 && lngExtra != 0)
	        	new LoadPlaces().execute(latExtra, lngExtra);
	        
	        lv.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> paretn, View view,
						int position, long id) {
					// getting values from selected ListItem
					String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
					
					Intent in = new Intent(getApplicationContext(), SinglePlaceActivity.class);
					in.putExtra(KEY_REFERENCE, reference);
					startActivity(in);
					
				}
			});
	 }
	 @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
		 getSupportMenuInflater().inflate(R.menu.google_place, menu);
		
		 return super.onCreateOptionsMenu(menu);
	 }
	 @Override
	 public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		 switch(item.getItemId()){
		 case R.id.google_place:
			 Intent maps_place = new Intent(this, LocationActivity.class);
			 maps_place.putExtra(TAG_LATITUDE, Double.valueOf(latExtra));
			 maps_place.putExtra(TAG_LONGITUDE, Double.valueOf(lngExtra));
			 Log.d("Location Extra", String.valueOf(latExtra) + ", " + String.valueOf(lngExtra));
			 startActivity(maps_place);
			 return true;
		 }
		return false;
	 }
	 class LoadPlaces extends AsyncTask<Double, Void, String>{

		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(GooglePlacesActivity.this);
            pDialog.setTitle("Xin chờ");
            pDialog.setMessage("Đang tải danh sách địa điểm...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
		@Override
		protected String doInBackground(Double... agrs) {
			double lat = agrs[0];
			double lng = agrs[1];
			
			googlePlaces = new GooglePlaces();
            try {
            	 String types = "cafe|food|restaurant";
            	 double radius = 1000;
            	 nearPlaces = googlePlaces.search(lat, lng, radius, types);
            } catch (Exception e) {
                e.printStackTrace();
            }
			
			return null;
		}
		protected void onPostExecute(String file_url) {
	        // dismiss the dialog after getting all products
	        pDialog.dismiss();
	        // updating UI from Background Thread
	        runOnUiThread(new Runnable() {
	            public void run() {
	                /**
	                 * Updating parsed Places into LISTVIEW
	                 * */
	                // Get json response status
	                String status = nearPlaces.status;

	                // Check for all possible status
	                if(status.equals("OK")){
	  
	                    // Successfully got places details
	                    if (nearPlaces.results != null) {
	                        // loop through each place
	                        for (Place p : nearPlaces.results) {
	                            HashMap<String, String> map = new HashMap<String, String>();

	                            // Place reference won't display in listview - it will be hidden
	                            // Place reference is used to get "place full details"
	                            map.put(KEY_REFERENCE, p.reference);

	                            // Place name
	                            map.put(KEY_NAME, p.name);

	                            // adding HashMap to ArrayList
	                            placesListItems.add(map);
	                        }
	                        // list adapter
	                        ListAdapter adapter = new SimpleAdapter(GooglePlacesActivity.this, placesListItems,
	                                R.layout.list_item,
	                                new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
	                                        R.id.reference, R.id.name });

	                        // Adding data into listview
	                        lv.setAdapter(adapter);
	                    }
	                }
	                else if(status.equals("ZERO_RESULTS")){
	                    // Zero results found
	                    alert.showAlertDialog(GooglePlacesActivity.this, "Địa Điểm Xung Quanh",
	                            "Không có nơi nào được tìm thấy.",
	                            false);
	                    //startActivity(new Intent(GooglePlacesActivity.this, AllFoodsActivity.class));
	                }
	                else if(status.equals("UNKNOWN_ERROR"))
	                {
	                    alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
	                            "Không biết lỗi xảy ra.",
	                            false);
	                    //startActivity(new Intent(GooglePlacesActivity.this, AllFoodsActivity.class));
	                }
	                else if(status.equals("OVER_QUERY_LIMIT"))
	                {
	                    alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
	                            "Truy vấn tới Google Place bị giới hạn.",
	                            false);
	                    //startActivity(new Intent(GooglePlacesActivity.this, AllFoodsActivity.class));
	                }
	                else if(status.equals("REQUEST_DENIED"))
	                {
	                    alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
	                            "Yêu cầu bị từ chối.",
	                            false);
	                    //startActivity(new Intent(GooglePlacesActivity.this, AllFoodsActivity.class));
	                }
	                else if(status.equals("INVALID_REQUEST"))
	                {
	                    alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
	                            "Yêu cầu không hợp lệ.",
	                            false);
	                    //startActivity(new Intent(GooglePlacesActivity.this, AllFoodsActivity.class));
	                }
	                else
	                {
	                    alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
	                            "Xin lỗi đã xảy ra lỗi.",
	                            false);
	                    //startActivity(new Intent(GooglePlacesActivity.this, AllFoodsActivity.class));
	                }
	            }
	        });

	    }
	 }
}
